package com.imooc.interceptor;


import com.imooc.utils.IMOOCJSONResult;
import com.imooc.utils.JsonUtils;
import com.imooc.utils.RedisOperator;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.OutputStream;

/**
 * 拦截用户会话
 */
public class UserTokenInterceptor implements HandlerInterceptor {

    @Autowired
    private RedisOperator redisOperator;

    private final String REDIS_USER_TOKEN = "redis_user_token";


    /**
     * 拦截请求，在访问Controller调用之前。
     * 在该方法中进行 用户权限的验证。
     * 返回 false : 请求被拦截，被驳回，验证出现问题
     * 返回 true : 请求成功通过验证校验
     */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String userToken = request.getHeader("headerUserToken");
        String userId = request.getHeader("headerUserId");

        if(StringUtils.isNotBlank(userId) &&
                StringUtils.isNotBlank(userToken)){
            // 获取TokenId
            String uniqueToken = redisOperator.get(REDIS_USER_TOKEN+":"+userId);
            if(StringUtils.isBlank(uniqueToken)){
                returnErrorResponse(response,IMOOCJSONResult.errorMsg("请登录..."));
                return false;
            }
            // 验证TokenId
            if(!uniqueToken.equals(userToken)){
                returnErrorResponse(response,IMOOCJSONResult.errorMsg("账号在异地登录..."));
                return false;
            }
        }else{
            returnErrorResponse(response,IMOOCJSONResult.errorMsg("请登录..."));
            return false;
        }
        // 验证通过，请求放行
        return true;
    }

    /**
     * 获取到 Response的输出流，将错误信息 输入到 输出流中
     * @param response 响应
     * @param result 错误信息
     */
    public void returnErrorResponse(HttpServletResponse response,
                                    IMOOCJSONResult result){
        OutputStream out = null;
        try {
            // 设置响应的字符集
            response.setCharacterEncoding("utf-8");
            // 设置响应内容的数据结构
            response.setContentType("text/json");
            out = response.getOutputStream();
            out.write(JsonUtils.objectToJson(result).getBytes("utf-8"));
            out.flush();
        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            try {
                if(out!=null){
                    out.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    /**
     * 请求访问Controller之后，渲染视图之前
     */
    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {

    }

    /**
     * 请求访问Controller之后，视图渲染之后
     */
    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {

    }
}
